package com.link.base.base.accnt.service;

import com.link.base.user.model.CoreUser;
import com.link.base.base.accnt.dao.mybatis.mapper.AccntFollowMapper;
import com.link.base.base.accnt.model.AccntFollow;
import com.link.base.base.accnt.model.Account;
import com.link.base.base.common.model.Attachment;
import com.link.base.base.common.service.AttachmentService;
import com.link.base.base.image.model.Image;
import com.link.base.base.image.service.AppImageService;
import com.link.base.base.reception.model.Reception;
import com.link.base.base.reception.service.ReceptionService;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.dao.siebel.mapper.BasicMapperSiebel;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.DateUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author  unknwon
 * @date:   2018/11/7 15:39
 * @version 1.0
 */

@Service
public class AccntFollowServiceImpl extends BasicServiceImpl<AccntFollow>
        implements AccntFollowService {

    @Resource
    private AccntFollowMapper accntFollowMapper;

    @Resource
    private KeyGenerateService keyGenerateService;

    @Resource
    private AppImageService appImageService;
    @Resource
    private AttachmentService attachmentService;

    @Resource
    private ReceptionService receptionService;

    private String imagModule = "GuideFollowUp";

    @Override
    public BasicMapper<AccntFollow> getBasicMapper() {
        return accntFollowMapper;
    }

    @Override
    public BasicMapperSiebel<AccntFollow> getSiebelBasicMapper() throws Exception {
        return null;
    }

    @Override
    public void insert(AccntFollow entity) throws Exception {
        beforInsert(entity);
        BasicModel model = (BasicModel) entity;
        if (null == model.getId()) {
            model.setId(keyGenerateService.keyGenerate());
        }
        if (!checkData(entity)) {
            // 进行数据校验
            throw new ServiceException("PUBLIC-001");
        }
        getBasicMapper().insert(entity);
        this.afterInsert(entity);
    }

    @Override
    public void beforInsert(AccntFollow entity) throws Exception {
        if (StringUtils.isNull(entity.getCreateTime())) {
            // 记录时间
            entity.setCreateTime(DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
        }

        if (null != entity.getOptyId()) {
            Reception guideOpty = new Reception();
            guideOpty.setId(entity.getOptyId());
            guideOpty = receptionService.queryById(guideOpty);
            if (guideOpty != null) {
                entity.setCrmCustId(guideOpty.getAccountId());
            }
        }
    }

    @Override
    public void afterInsert(AccntFollow entity) throws Exception {
        // 将记录时间回写到客户上最后跟进时间字段
        accntFollowMapper.updateAccntLastFollowTime(entity);
    }

    /**
     * 新建客户时创建一条默认的跟进信息 parm:source : QIDIAN,CRM
     * @param accnt
     * @param source
     * @param message
     * @param reception
     * @throws Exception
     */
    @Override
    public void insertFollowWhenInsertAccnt(Account accnt, String source, String message, Reception reception) throws Exception {
        // 先插入数据库
        AccntFollow entity = new AccntFollow();
        entity.setId(keyGenerateService.keyGenerate());
        entity.interfaceCreateData(accnt.getCreatedBy(), accnt.getCreatedBy(), accnt.getCorpid());
        entity.setCrmCustId(accnt.getId());
        entity.setMsgType("TEXT");
        entity.setMessage(message);
        entity.setVioceMsgSize("0");
        entity.setIsFollowMine("Y");
        entity.setCreateTime(DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
        String sourceFrom = "CRM";
        if (sourceFrom.equals(source)) {
            CoreUser user = UserUtil.getUser();
            entity.setName(user.getFirstName());
            // 创建人企点id
            entity.setCrmCreatedByOpenId(user.getQdUserOpenid());
            entity.setCrmCreatedBy(user.getId());
            if (reception != null) {
                entity.setOptyId(reception.getId());
            }
            this.insert(entity);
        } else {
            throw new ServiceException("ACCT-001");
        }
    }

    /**
     * 通过id查询跟进记录
     * @param entity
     * @return
     * @throws Exception
     */
    @Override
    public AccntFollow queryById(AccntFollow entity) throws Exception {
        entity = super.queryById(entity);
        Image image = new Image();
        image.setParentid(entity.getId());
        image.setModule(imagModule);
        List<Image> imageList = appImageService.queryAll(image);
        entity.setImageList(imageList);
        Attachment guideAttachment = attachmentService.queryVoiceAttachmentByHeadId(entity.getId());
        entity.setVoiceAttachment(guideAttachment);
        return entity;
    }

    /**
     * 查询跟进记录列表（分页）
     * @param entity
     * @return entity
     */
    @Override
    public List<AccntFollow> queryByExamplePage(AccntFollow entity) throws Exception {
        List<AccntFollow> list = super.queryByExamplePage(entity);
        if (list != null && list.size() > 0) {
            Image image = null;
            Attachment guideAttachment = null;
            for (AccntFollow accntFollow : list) {
                // 查询图片附件
                image = new Image();
                image.setParentid(accntFollow.getId());
                image.setModule(imagModule);
                List<Image> imageList = appImageService.queryAll(image);
                accntFollow.setImageList(imageList);
                guideAttachment = attachmentService.queryVoiceAttachmentByHeadId(accntFollow.getId());
                accntFollow.setVoiceAttachment(guideAttachment);
            }
        }
        return list;
    }

    /**
     * 查询跟进记录列表
     * @param entity
     * @return List
     */
    @Override
    public List<AccntFollow> queryAll(AccntFollow entity) throws Exception {
        List<AccntFollow> list = super.queryAll(entity);
        if (list != null && list.size() > 0) {
            Image image = null;
            Attachment guideAttachment = null;
            for (AccntFollow accntFollow : list) {
                // 查询图片附件
                image = new Image();
                image.setParentid(accntFollow.getId());
                image.setModule(imagModule);
                List<Image> imageList = appImageService.queryAll(image);
                accntFollow.setImageList(imageList);
                guideAttachment = attachmentService.queryVoiceAttachmentByHeadId(accntFollow.getId());
                accntFollow.setVoiceAttachment(guideAttachment);
            }
        }
        return list;
    }

    /**
     * 通过id删除数据
     * @param entity
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = BasicServiceException.class)
    public void deleteById(AccntFollow entity) throws Exception {
        // 如果是文本,则直接删除跟进记录
        String textType = "TEXT";
        if (textType.equals(entity.getMsgType())) {
            // 删除CRM中的跟进
            super.deleteById(entity);
        }
        // 如果是音频,则删除跟进记录及其附件
        String voiceType = "VOICE";
        if (voiceType.equals(entity.getMsgType())) {
            //删除语音附件
            attachmentService.deleteById(entity.getVoiceAttachment());
            //删除跟进消息
            super.deleteById(entity);
        }
        // 如果是图片,
        String imgType = "IMG";
        if (imgType.equals(entity.getMsgType())) {
            //根据id查询当前跟进,获取其所有的附件
            AccntFollow tempFlow = this.queryById(entity);
            if (tempFlow.getImageList().size() == 1) {
                //如果只有1张,则删除附件记录及跟进记录
                appImageService.deleteById(entity.getImageList().get(0));
                super.deleteById(entity);
            } else if (tempFlow.getImageList().size() > 1) {
                //如果大于1张,则只删除附件记录,则只删除当前传入的附件记录
                appImageService.deleteById(entity.getImageList().get(0));
            }
        }
    }
}
